package net.entelijan.cobean.filesel;

import java.awt.Component;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import net.entelijan.cobean.core.DialogReturnValue;

public class DefaultFileChooser implements IFileChooser {

	private JFileChooser chooser = new JFileChooser();

	public DefaultFileChooser() {
		super();
	}

	@Override
	public File getSelectedFile() {
		return this.chooser.getSelectedFile();
	}

	@Override
	public void setCurrentDirectory(File currentDirectory) {
		this.chooser.setCurrentDirectory(currentDirectory);
	}

	@Override
	public void setFileFilter(IFileFilter fileFilter) {
		this.chooser.setFileFilter(wrapFilter(fileFilter));
	}

	@Override
	public void setFileSelectionMode(FileSelectionMode fileSelectionMode) {
		this.chooser.setFileSelectionMode(fileSelectionMode.getSwingConstant());
	}

	@Override
	public void setSelectedFile(File selFile) {
		this.chooser.setSelectedFile(selFile);
	}

	@Override
	public DialogReturnValue showOpenDialog(Component parent) {
		final int re = chooser.showOpenDialog(parent);
		if (re == JFileChooser.APPROVE_OPTION) {
			return DialogReturnValue.OK;
		} else {
			return DialogReturnValue.CANCEL;
		}
	}

	private FileFilter wrapFilter(final IFileFilter fileFilter) {
		return new WrappingFileFilter(fileFilter);
	}

	private static class WrappingFileFilter extends FileFilter {
		private final IFileFilter fileFilter;

		private WrappingFileFilter(IFileFilter fileFilter) {
			this.fileFilter = fileFilter;
		}

		@Override
		public String getDescription() {
			return fileFilter.getDescription();
		}

		@Override
		public boolean accept(File f) {
			return fileFilter.accept(f);
		}
	}


}
